<script setup lang="ts">
import type { formData } from '@/types/update_form_data'
import { computed, ref, watch } from 'vue'

import { Format, Validate } from 'ls.utils.core/src/'

// 深拷贝函数
const deepClone = <T,>(obj: T): T => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime()) as T
  if (obj instanceof Array) return obj.map((item) => deepClone(item)) as T
  if (obj instanceof Object) {
    const cloned = {} as T
    Object.keys(obj).forEach((key) => {
      cloned[key] = deepClone(obj[key])
    })
    return cloned
  }
  return obj
}
Format.formatMoney(12341234.246, '$', 2)
Validate.mobileCheck('123456')
const props = defineProps<{
  data?: formData
}>()

//添加一层，不直接修改props  父子组件同步更新
// const emit = defineEmits<{
//   (e: 'update:data', value?: formData)
//   (e: 'submit')
// }>()

// const formModal = computed({
//   get: () => props.data,
//   父组件 v-model:data 时候本行才有效
//   set: (value) => emit('update:data', value)
// })

// const submit = () => {
//   emit('submit')
// }
//父子组件同步更新
//or
//父子组件不同步更新
const emit = defineEmits<{
  (e: 'submit', value?: formData)
}>()

const formModal = ref<formData>({
  id: 0,
  name: '',
  age: 0,
  jobs: []
})

watch(
  () => props.data,
  (newData) => {
    formModal.value = deepClone(newData)
  },
  { immediate: true }
)

const submit = () => {
  console.log(formModal.value)
  emit('submit', deepClone(formModal.value))
}
//父子组件不同步更新

const addJob = () => {
  formModal.value.jobs.push({
    city: '',
    companyName: ''
  })
}
const delJob = () => {
  if (formModal.value && formModal.value.jobs) formModal.value.jobs.splice(formModal.value.jobs.length - 1, 1)
}
</script>

<template>
  <h3>子组件： 动态渲染保存表单中子项数据 {{ formModal }}</h3>

  <a-form :model="formModal">
    <a-form-item name="name">
      <a-input v-model:value="formModal.name"></a-input>
    </a-form-item>
    <a-form-item name="age">
      <a-input v-model:value="formModal.age"></a-input>
    </a-form-item>
    <a-row>
      <a-col :span="12"><a-button @click="addJob">+</a-button></a-col>
      <a-col :span="12"><a-button @click="delJob" v-show="formModal.jobs.length != 0">-</a-button></a-col>
    </a-row>
    <template v-if="formModal.jobs" v-for="job in formModal.jobs">
      <a-form-item name="companyName">
        <a-input v-model:value="job.companyName"></a-input>
      </a-form-item>
      <a-form-item name="city">
        <a-input v-model:value="job.city"></a-input>
      </a-form-item>
    </template>
    <a-row>
      <a-button type="primary" @click="submit">提交</a-button>
    </a-row>
  </a-form>
</template>
